<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Auth;

class H5Authenticate
{
    public function handle($request, Closure $next, ...$guards)
    {
        // 4001 与前端约定跳到登录页
        if (Auth::guard('h5')->guest()) {
            $responseData = [
                'code' => 4001,
                'msg'  => '用户未授权'
            ];
            return response()->json($responseData)->header('Content-Type', 'application/json;charset=utf-8');
        }

        $res = Auth::guard('h5')->check();
        if ($res !== true) {
            $responseData = [
                'code' => 4001,
                'msg'  => $res['msg'] ?? '登录失败'
            ];
            return response()->json($responseData)->header('Content-Type', 'application/json;charset=utf-8');
        }

        $request->userInfo = Auth::guard('h5')->user();
        $request->guard    = 'h5';

        return $next($request);
    }
}